import { Form, Input, message, Modal, Select, Upload } from 'antd';
import React, { useContext, useEffect } from 'react';
import AddDirModal from './addDirModal';
import { addContentDir } from '@/services/contentMng/contentDirectory';
import { DirContext } from '.';
import { ContentDirListItem } from '@/types/contentMng/contentDirectory';
import { isJson } from '@/utils/common';
import { uniqueId } from 'lodash';

interface IProps {
  open: boolean;
  onClose: (options?: { isRefresh: boolean }) => void;
  tempId: string;
  level: number;
  data: ContentDirListItem | null;
}

const AddFirstLevelDir = (props: IProps) => {
  const { open, onClose, tempId, level, data } = props;

  const [form] = Form.useForm();
  const dirConfigStr = sessionStorage.getItem('dirConfig');
  const dirConfig = isJson(dirConfigStr) ? JSON.parse(dirConfigStr!) : [];
  const dirFieldsList = dirConfig.filter(i => +i.level == +level);

  useEffect(() => {
    if (!open) return;
    form?.setFieldsValue({
      contents: dirFieldsList,
    });
  }, [open]);

  const onCancel = () => {
    form.resetFields();
    onClose();
  };

  const onSave = async () => {
    let values = await form.validateFields();
    let params = {
      catalogueName: values.catalogueName,
      templateSid: tempId,
      parentSid: data?.sid,
      catalogueLevel: level,
      contents: values.contents,
    };
    let result = await addContentDir(params);
    if (result.statusCode === '0') {
      form.resetFields();
      onClose({ isRefresh: true });
      message.success('新增成功');
    }
  };

  return (
    <AddDirModal
      title={`添加${level}级目录`}
      open={open}
      onCancel={onCancel}
      onOk={onSave}
      formProps={{ form }}
      fieldsList={dirFieldsList}
    />
  );
};

export default AddFirstLevelDir;
